import React, { useState, useEffect } from 'react';
import { Card, Row, Col, Table, Tag, Space, Button, Input, Badge, Progress, Tooltip } from 'antd';
import { 
  SearchOutlined, 
  ReloadOutlined, 
  EyeOutlined, 
  SettingOutlined,
  BuildOutlined,
  ThunderboltOutlined,
  FireOutlined,
  VideoCameraOutlined,
  CarOutlined,
  HomeOutlined
} from '@ant-design/icons';
import { useNavigate } from 'react-router-dom';
import type { ColumnsType } from 'antd/es/table';

const { Search } = Input;

// 子系统数据接口
interface SubsystemData {
  id: string;
  systemCode: string;
  systemName: string;
  description: string;
  status: 'online' | 'offline' | 'fault' | 'maintenance';
  deviceCount: number;
  onlineDevices: number;
  faultDevices: number;
  lastUpdate: string;
  category: string;
}

// 系统图标映射
const systemIconMap: { [key: string]: React.ReactNode } = {
  'ESS': <ThunderboltOutlined style={{ color: '#1890ff' }} />,
  'HVAC': <HomeOutlined style={{ color: '#52c41a' }} />,
  'FPS': <FireOutlined style={{ color: '#ff4d4f' }} />,
  'VSS': <VideoCameraOutlined style={{ color: '#722ed1' }} />,
  'PMS': <CarOutlined style={{ color: '#fa8c16' }} />,
  'ACS': <BuildOutlined style={{ color: '#13c2c2' }} />,
};

// 模拟子系统数据
const mockSubsystemData: SubsystemData[] = [
  {
    id: 'SYS001',
    systemCode: 'ESS',
    systemName: '电梯系统',
    description: '楼宇电梯监控与管理系统',
    status: 'online',
    deviceCount: 6,
    onlineDevices: 4,
    faultDevices: 1,
    lastUpdate: '2024-01-20 14:30:25',
    category: '设备管理'
  },
  {
    id: 'SYS002',
    systemCode: 'HVAC',
    systemName: '暖通空调系统',
    description: '中央空调与通风系统管理',
    status: 'online',
    deviceCount: 24,
    onlineDevices: 22,
    faultDevices: 0,
    lastUpdate: '2024-01-20 14:28:15',
    category: '环境控制'
  },
  {
    id: 'SYS003',
    systemCode: 'FPS',
    systemName: '消防系统',
    description: '火灾报警与消防设备管理',
    status: 'online',
    deviceCount: 156,
    onlineDevices: 154,
    faultDevices: 2,
    lastUpdate: '2024-01-20 14:32:10',
    category: '安全防护'
  },
  {
    id: 'SYS004',
    systemCode: 'VSS',
    systemName: '视频监控系统',
    description: '安防监控与录像管理',
    status: 'online',
    deviceCount: 89,
    onlineDevices: 85,
    faultDevices: 1,
    lastUpdate: '2024-01-20 14:29:45',
    category: '安全防护'
  },
  {
    id: 'SYS005',
    systemCode: 'PMS',
    systemName: '停车管理系统',
    description: '智能停车场管理与收费',
    status: 'fault',
    deviceCount: 12,
    onlineDevices: 8,
    faultDevices: 3,
    lastUpdate: '2024-01-20 14:15:30',
    category: '交通管理'
  },
  {
    id: 'SYS006',
    systemCode: 'ACS',
    systemName: '门禁系统',
    description: '出入口控制与权限管理',
    status: 'maintenance',
    deviceCount: 45,
    onlineDevices: 0,
    faultDevices: 0,
    lastUpdate: '2024-01-20 10:00:00',
    category: '安全防护'
  }
];

const SubsystemList: React.FC = () => {
  const [subsystemData, setSubsystemData] = useState<SubsystemData[]>(mockSubsystemData);
  const [loading, setLoading] = useState(false);
  const [searchText, setSearchText] = useState('');
  const navigate = useNavigate();

  // 状态统计
  const getStatusStatistics = () => {
    const total = subsystemData.length;
    const online = subsystemData.filter(item => item.status === 'online').length;
    const offline = subsystemData.filter(item => item.status === 'offline').length;
    const fault = subsystemData.filter(item => item.status === 'fault').length;
    const maintenance = subsystemData.filter(item => item.status === 'maintenance').length;
    
    return { total, online, offline, fault, maintenance };
  };

  const statistics = getStatusStatistics();

  // 状态标签渲染
  const renderStatus = (status: string) => {
    const statusMap = {
      online: { color: 'green', text: '正常运行' },
      offline: { color: 'red', text: '离线' },
      fault: { color: 'orange', text: '故障' },
      maintenance: { color: 'blue', text: '维护中' }
    };
    
    const config = statusMap[status as keyof typeof statusMap];
    return <Tag color={config.color}>{config.text}</Tag>;
  };

  // 设备状态渲染
  const renderDeviceStatus = (record: SubsystemData) => {
    const onlineRate = record.deviceCount > 0 ? (record.onlineDevices / record.deviceCount) * 100 : 0;
    const faultRate = record.deviceCount > 0 ? (record.faultDevices / record.deviceCount) * 100 : 0;
    
    let progressColor = '#52c41a';
    if (onlineRate < 80) progressColor = '#faad14';
    if (onlineRate < 60) progressColor = '#ff4d4f';
    
    return (
      <div>
        <div style={{ marginBottom: 4 }}>
          <span>在线: {record.onlineDevices}/{record.deviceCount}</span>
          {record.faultDevices > 0 && (
            <span style={{ marginLeft: 8, color: '#ff4d4f' }}>
              故障: {record.faultDevices}
            </span>
          )}
        </div>
        <Progress 
          percent={onlineRate} 
          size="small" 
          strokeColor={progressColor}
          format={() => `${Math.round(onlineRate)}%`}
        />
      </div>
    );
  };

  // 表格列配置
  const columns: ColumnsType<SubsystemData> = [
    {
      title: '系统图标',
      key: 'icon',
      width: 80,
      render: (_, record) => (
        <div style={{ fontSize: '24px', textAlign: 'center' }}>
          {systemIconMap[record.systemCode] || <BuildOutlined />}
        </div>
      ),
    },
    {
      title: '系统名称',
      dataIndex: 'systemName',
      key: 'systemName',
      width: 150,
      render: (text, record) => (
        <div>
          <div style={{ fontWeight: 'bold' }}>{text}</div>
          <div style={{ fontSize: '12px', color: '#666' }}>{record.systemCode}</div>
        </div>
      ),
    },
    {
      title: '系统描述',
      dataIndex: 'description',
      key: 'description',
      width: 200,
    },
    {
      title: '分类',
      dataIndex: 'category',
      key: 'category',
      width: 120,
      render: (category) => <Tag>{category}</Tag>,
    },
    {
      title: '运行状态',
      dataIndex: 'status',
      key: 'status',
      width: 120,
      render: renderStatus,
    },
    {
      title: '设备状态',
      key: 'deviceStatus',
      width: 180,
      render: (_, record) => renderDeviceStatus(record),
    },
    {
      title: '最后更新',
      dataIndex: 'lastUpdate',
      key: 'lastUpdate',
      width: 160,
    },
    {
      title: '操作',
      key: 'action',
      width: 200,
      render: (_, record) => (
        <Space size="small">
          <Button 
            type="link" 
            icon={<EyeOutlined />} 
            size="small"
            onClick={() => handleViewSystem(record)}
          >
            查看
          </Button>
          <Button 
            type="link" 
            icon={<SettingOutlined />} 
            size="small"
            onClick={() => handleManageSystem(record)}
          >
            管理
          </Button>
        </Space>
      ),
    },
  ];

  // 处理查看系统
  const handleViewSystem = (record: SubsystemData) => {
    // 根据系统代码跳转到对应的系统页面
    const routeMap: { [key: string]: string } = {
      'ESS': '/subsystem/elevator',
      'HVAC': '/subsystem/hvac',
      'FPS': '/subsystem/fire',
      'VSS': '/subsystem/video',
      'PMS': '/subsystem/parking',
      'ACS': '/subsystem/access'
    };
    
    const route = routeMap[record.systemCode];
    if (route) {
      navigate(route);
    } else {
      console.log('查看系统:', record);
    }
  };

  // 处理管理系统
  const handleManageSystem = (record: SubsystemData) => {
    console.log('管理系统:', record);
    // 这里可以打开系统管理弹窗
  };

  // 刷新数据
  const handleRefresh = () => {
    setLoading(true);
    // 模拟API调用
    setTimeout(() => {
      setLoading(false);
    }, 1000);
  };

  // 过滤数据
  const filteredData = subsystemData.filter(item => {
    const matchSearch = item.systemName.toLowerCase().includes(searchText.toLowerCase()) ||
                       item.systemCode.toLowerCase().includes(searchText.toLowerCase()) ||
                       item.description.toLowerCase().includes(searchText.toLowerCase());
    return matchSearch;
  });

  return (
    <div style={{ padding: '0' }}>
      {/* 统计卡片 */}
      <Row gutter={16} style={{ marginBottom: 24 }}>
        <Col span={6}>
          <Card>
            <div style={{ display: 'flex', alignItems: 'center' }}>
              <Badge status="processing" />
              <div style={{ marginLeft: 8 }}>
                <div style={{ fontSize: '24px', fontWeight: 'bold' }}>{statistics.total}</div>
                <div style={{ color: '#666' }}>子系统总数</div>
              </div>
            </div>
          </Card>
        </Col>
        <Col span={6}>
          <Card>
            <div style={{ display: 'flex', alignItems: 'center' }}>
              <Badge status="success" />
              <div style={{ marginLeft: 8 }}>
                <div style={{ fontSize: '24px', fontWeight: 'bold', color: '#3f8600' }}>{statistics.online}</div>
                <div style={{ color: '#666' }}>正常运行</div>
              </div>
            </div>
          </Card>
        </Col>
        <Col span={6}>
          <Card>
            <div style={{ display: 'flex', alignItems: 'center' }}>
              <Badge status="error" />
              <div style={{ marginLeft: 8 }}>
                <div style={{ fontSize: '24px', fontWeight: 'bold', color: '#cf1322' }}>{statistics.fault}</div>
                <div style={{ color: '#666' }}>故障系统</div>
              </div>
            </div>
          </Card>
        </Col>
        <Col span={6}>
          <Card>
            <div style={{ display: 'flex', alignItems: 'center' }}>
              <Badge status="warning" />
              <div style={{ marginLeft: 8 }}>
                <div style={{ fontSize: '24px', fontWeight: 'bold', color: '#1890ff' }}>{statistics.maintenance}</div>
                <div style={{ color: '#666' }}>维护中</div>
              </div>
            </div>
          </Card>
        </Col>
      </Row>

      {/* 子系统列表 */}
      <Card 
        title="子系统列表"
        extra={
          <Space>
            <Search
              placeholder="搜索系统名称、代码或描述"
              value={searchText}
              onChange={(e) => setSearchText(e.target.value)}
              style={{ width: 250 }}
              allowClear
            />
            <Button 
              icon={<ReloadOutlined />} 
              onClick={handleRefresh}
              loading={loading}
            >
              刷新
            </Button>
          </Space>
        }
      >
        <Table
          columns={columns}
          dataSource={filteredData}
          rowKey="id"
          loading={loading}
          pagination={{
            total: filteredData.length,
            pageSize: 10,
            showSizeChanger: true,
            showQuickJumper: true,
            showTotal: (total, range) => `第 ${range[0]}-${range[1]} 条/共 ${total} 条`,
          }}
          scroll={{ x: 1200 }}
        />
      </Card>
    </div>
  );
};

export default SubsystemList;